<?php

namespace App\Console\Commands;

use App\Models\WordVideo;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;

class GenerateAudio extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'gen-audio';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '生成单词音频';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $disk = Storage::disk('oss');
        WordVideo::where('is_sync', 0)->chunk(100, function ($wordVideos) use ($disk){
            /** @var WordVideo $wordVideo */
            foreach($wordVideos as $wordVideo){

                $parsed = parse_url($wordVideo->video_url);
                $path = $parsed['path'] ?? '';
                $query = isset($parsed['query']) ? '?' . $parsed['query'] : '';
                $fileName= substr($path . $query,1);

                // 1. 从百度获取音频流
                $audioStream = $this->fetchBaiduAudio($wordVideo->word);
                $result =$disk->put($fileName, $audioStream);

                $wordVideo->is_sync = 1;
                $wordVideo->save();
            }
        });
    }

    protected function fetchBaiduAudio(string $text)
    {
        $client = new Client([
            'headers' => [
                'Referer' => 'https://fanyi.baidu.com/',
                'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
            ]
        ]);

        $response = $client->get('https://fanyi.baidu.com/gettts', [
            'query' => [
                'lan' => 'uk',
                'text' => $text,
                'spd' => 3,
                'source' => 'web'
            ]
        ]);

        if ($response->getStatusCode() !== 200) {
            throw new \Exception('百度音频接口请求失败');
        }

        return $response->getBody()->getContents();
    }
}
